﻿namespace Bigway.Common.Utils;

public static class UrlUtils
{
    public static string GetRelativeUrl(string? url)
    {
        url ??= "";
        url = url.Trim();
        if (string.IsNullOrEmpty(url))
            return "";

        if (url.StartsWith("http://"))
        {
            url = url["http://".Length..];
        }
        if (url.StartsWith("https://"))
        {
            url = url["https://".Length..];
        }

        var indexOfSlash = url.IndexOf('/');
        return indexOfSlash != -1 ? url[(indexOfSlash+1)..] : "";
    }

    public static bool IsAbsoluteUrl(string? url)
    {
        return url != null && 
               (url.StartsWith("http://") || url.StartsWith("https://"));
    }

    public static string GetAbsoluteUrl(string? baseUrl, string? relativeUrl)
    {
        baseUrl ??= "";
        relativeUrl ??= "";
        baseUrl = baseUrl.Trim();
        relativeUrl = relativeUrl.Trim();
        if (IsAbsoluteUrl(relativeUrl))
            relativeUrl = GetRelativeUrl(relativeUrl);

        if (relativeUrl.StartsWith('/'))
            relativeUrl = relativeUrl[1..];

        if (string.IsNullOrEmpty(baseUrl) || !IsAbsoluteUrl(baseUrl))
            return "";
        
        relativeUrl = relativeUrl.Trim();
        return baseUrl.EndsWith('/') ? baseUrl + relativeUrl : $"{baseUrl}/{relativeUrl}";
    }
}